import time
import urllib
import gevent
from gevent import monkey


class GeventDemo:
    def f(self, n):
        for i in range(n):
            print(gevent.getcurrent(), i)

    def download(self, filename, url):
        print('url is %s' % url)
        resp = urllib.request.urlopen(url)
        content = resp.read()
        print('%d bytes received from %s.' % (len(content), url))
        with open(filename, 'wb') as f:
            f.write(content)

    def gsleep(self, n):
        for i in range(n):
            print(gevent.getcurrent(), i)
            gevent.sleep(0.5)

    def tsleep(self, n):
        for i in range(n):
            print(gevent.getcurrent(), i)
            time.sleep(0.5)

    def _test_spawn(self):
        """
        gd = GeventDemo()
        gd._test_spawn()
        """
        g1 = gevent.spawn(self.f, 5)
        g2 = gevent.spawn(self.f, 5)
        g3 = gevent.spawn(self.f, 5)
        g1.join()
        g2.join()
        g3.join()

    def _test_joinall(self):
        """
        gd = GeventDemo()
        gd._test_joinall()
        """
        # 有耗时操作时添加
        monkey.patch_all()
        gevent.joinall([
            gevent.spawn(self.download, './ext/cGevent/Download1.jpg',
                         'https://imgsa.baidu.com/news/q%3D100/sign=3c363f11a9cc7cd9fc2d30d909002104'
                         '/d058ccbf6c81800a8941adf2bb3533fa838b47a1.jpg'),
            gevent.spawn(self.download, './ext/cGevent/Download2.jpg',
                         'https://imgsa.baidu.com/news/q%3D100/sign=8d8768c464061d957b4633384bf50a5d'
                         '/d62a6059252dd42a0cb21057093b5bb5c8eab896.jpg')
        ])

    def _test_gsleep(self):
        """
        gd = GeventDemo()
        gd._test_gsleep()
        """
        g1 = gevent.spawn(self.gsleep, 5)
        g2 = gevent.spawn(self.gsleep, 5)
        g3 = gevent.spawn(self.gsleep, 5)
        g1.join()
        g2.join()
        g3.join()

    def _test_tsleep(self):
        """
        gd = GeventDemo()
        gd._test_tsleep()
        """
        monkey.patch_all()
        gevent.joinall([
            gevent.spawn(self.tsleep, 5),
            gevent.spawn(self.tsleep, 5),
            gevent.spawn(self.tsleep, 5)
        ])


if __name__ == '__main__':
    gd = GeventDemo()
    gd._test_tsleep()
